package com.itheima.service.store.impl;

import com.itheima.dao.store.QuestionItemDao;
import com.itheima.domain.store.QuestionItem;
import com.itheima.factory.MapperFactory;
import com.itheima.service.store.QuestionItemService;
import com.itheima.utils.UUIDUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class QuestionItemServiceImpl implements QuestionItemService {
    @Override
    public List<QuestionItem> findAll() throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        QuestionItemDao mapper = sqlSession.getMapper(QuestionItemDao.class);

        List<QuestionItem> list = mapper.findAll();
        sqlSession.close();

        return list;
    }

    @Override
    public QuestionItem findById(String id) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        QuestionItemDao mapper = sqlSession.getMapper(QuestionItemDao.class);

        QuestionItem questionItem = mapper.findById(id);
        sqlSession.close();
        return questionItem;
    }

    @Override
    public void save(QuestionItem questionItem) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        QuestionItemDao mapper = sqlSession.getMapper(QuestionItemDao.class);

        questionItem.setId(UUIDUtil.getSimpleUUID());
        mapper.save(questionItem);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void update(QuestionItem questionItem) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        QuestionItemDao mapper = sqlSession.getMapper(QuestionItemDao.class);

        mapper.update(questionItem);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void deleteById(String id) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        QuestionItemDao mapper = sqlSession.getMapper(QuestionItemDao.class);

        mapper.deleteById(id);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public List<QuestionItem> findByQuestionId(String questionId) throws Exception {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        QuestionItemDao mapper = sqlSession.getMapper(QuestionItemDao.class);

        List<QuestionItem> questionItems = mapper.findByQuestionId(questionId);

        sqlSession.close();
        return questionItems;
    }

    @Override
    public void clean() {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        QuestionItemDao mapper = sqlSession.getMapper(QuestionItemDao.class);

        mapper.clean();

        sqlSession.commit();
        sqlSession.close();
    }
}
